package com.fenghen.notfoelearning;

import com.intellij.notification.*;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.DialogWrapper;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class InitDialog extends DialogWrapper {
    private JLabel jLabel;
    private int countdown = 10; // 倒计时秒数
    private Timer timer;
    private JButton jButton;

    private static int launchCount = 0; // 记录插件启动次数
    private static final int MAX_LAUNCHES = 3; // 最大可强制关闭次数

    protected InitDialog() {
        super(true);
        setTitle("想学习？不可能");
        init();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        JPanel jPanel = new JPanel();
        jLabel = new JLabel("别真让你学到东西了");
        jPanel.add(jLabel);
        return jPanel;
    }

    @Override
    protected JComponent createSouthPanel() {
        JPanel jPanel = new JPanel();
        jButton = new JButton("牢底，学不了哈");
        jButton.addActionListener(e -> handleLaunch());
        jPanel.add(jButton);
        return jPanel;
    }

    private void handleLaunch() {
        launchCount++; // 增加启动次数

        if (launchCount <= MAX_LAUNCHES) {
            // 更新 Label 为倒计时信息
            jLabel.setText("程序将在 " + countdown + " 秒后关闭 IntelliJ IDEA。");

            // 创建并启动 Timer
            timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    countdown--;
                    jLabel.setText("程序将在 " + countdown + " 秒后关闭 IntelliJ IDEA。");

                    if (countdown <= 0) {
                        timer.stop(); // 停止计时器
                        System.exit(0); // 关闭 IDEA
                    }
                }
            });

            timer.start(); // 启动计时器
        } else {
            // 超过次数后，发送普通通知
            showNotification();
        }
    }

    private void showNotification() {
        // 显示普通通知
        NotificationGroup notificationGroup = new NotificationGroup("firstplugin_id", NotificationDisplayType.BALLOON, true);
        Notification notification = notificationGroup.createNotification(
                "光明神yyds",
                "在你的不懈努力下，我看到了你对学习的热爱，猛猛学，祝您好运！",
                String.valueOf(NotificationType.INFORMATION));
        Notifications.Bus.notify(notification);

        // 更新 JLabel 信息
        jLabel.setText("通知已发送，继续前行吧！");

        // 这里可以选择关闭对话框，或者不再显示
        // this.close(OK_EXIT_CODE); // Uncomment if you want to close the dialog after notification
    }
}